package com.dinree.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.TypeReference;
import com.base.library.Constant;
import com.base.library.TopBarBaseActivity;
import com.base.library.dialog.BottomDialog;
import com.base.library.http.HttpResult;
import com.base.library.http.upload.FileUploadObserver;
import com.base.library.http.upload.RetrofitClient;
import com.base.library.manager.DialogManager;
import com.base.library.manager.GlideImageManager;
import com.base.library.utils.JsonUtils;
import com.base.library.utils.StringUtils;
import com.bumptech.glide.Glide;
import com.dinree.R;
import com.dinree.api.UserApi;
import com.dinree.bean.UploadBean;
import com.dinree.bean.UserBean;
import com.dinree.databinding.ActivityCompanyAuthBinding;
import com.dinree.databinding.PhotoDialogBinding;
import com.jakewharton.rxbinding2.view.RxView;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.ResponseBody;

import static com.base.library.Constant.WINDOW_DURATION;

public class CompanyAuthActivity extends TopBarBaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    private ActivityCompanyAuthBinding activityCompanyAuthBinding;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private String path;
    private String name;
    private String company_name;
    private String company_address;
    private MaterialDialog dialog;
    private UserBean userBean;

    @Override
    public int getContentView() {
        return R.layout.activity_company_auth;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        activityCompanyAuthBinding = getContentViewBinding();
        userBean = realm.findFirst(UserBean.class);
        setTitle("经销商认证");
        setTopLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        RxView.clicks(activityCompanyAuthBinding.btnSubmit).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            submit();

        });
        RxView.clicks(activityCompanyAuthBinding.imgUpload).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            showPhoto();
        });
        loadData();
    }

    private void loadData() {
        if (userBean != null) {
            UserApi.getInstance(mContext).get_basic_info(userBean.user_id, userBean.user_token).subscribe(s -> {
                activityCompanyAuthBinding.companyAddress.setText(s.corp_address);
                activityCompanyAuthBinding.relName.setText(s.name);
                activityCompanyAuthBinding.companyName.setText(s.corpname);
                if (!StringUtils.isEmpty(s.corp_license)) {
                    GlideImageManager.getInstance(mContext).displayImage(s.corp_license, activityCompanyAuthBinding.imgUpload);
                }
            }, e -> {
            });

        }
    }

    private void submit() {
        name = activityCompanyAuthBinding.relName.getText().trim();
        company_name = activityCompanyAuthBinding.companyName.getText().trim();
        company_address = activityCompanyAuthBinding.companyAddress.getText().trim();
        if (StringUtils.isEmpty(name)) {
            showMsg("真实姓名不能为空");
            return;
        }
        if (StringUtils.isEmpty(company_name)) {
            showMsg("企业名字不能为空");
            return;
        }
        if (StringUtils.isEmpty(company_address)) {
            showMsg("企业地址不能为空");
            return;
        }
        if (StringUtils.isEmpty(path)) {
            showMsg("营业执照不能为空");
            return;
        }
        UserApi.getInstance(mContext).dealer_verify(userBean.user_id, userBean.user_token, name, company_name, company_address, path).subscribe(s -> {
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
        }, e -> {
        });
    }

    private void upload() {
        dialog = DialogManager.showProgress(mContext,"上传图片","请稍后……");
        String url = Constant.HOST + "epsea/public/api/user/upload_file?category=corplicense";
        File file = new File(path);
        RetrofitClient.getInstance().upLoadFile(url, file, new FileUploadObserver<ResponseBody>() {
            @Override
            public void onUpLoadSuccess(ResponseBody responseBody) {
                try {
                    if (userBean != null) {
                        HttpResult<UploadBean> httpResult = JsonUtils.getInstance().fromJson(responseBody.string(), new TypeReference<HttpResult<UploadBean>>() {
                        });
                        if (httpResult != null) {
                            if (httpResult.code == 0) {
                                path = httpResult.data.url;
                            } else {
                                path = null;
                                showMsg("营业执照上传失败");
                                dialog.dismiss();
                            }
                        } else {
                            path = null;
                            showMsg("营业执照上传失败");
                            dialog.dismiss();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }

            @Override
            public void onUpLoadFail(Throwable e) {
                path = null;
                showMsg("营业执照上传失败");
                dialog.dismiss();
            }

            @Override
            public void onProgress(int progress) {
            }
        });
    }

    private void showPhoto() {
        BottomDialog bottomDialog = new BottomDialog(mContext, R.layout.photo_dialog);
        PhotoDialogBinding photoDialogBinding = bottomDialog.getViewBinding();
        RxView.clicks(photoDialogBinding.picture).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
//                takePhoto.onPickFromGalleryWithCrop(imageUri,getCropOptions());
            CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(1080).create();
            takePhoto.onEnableCompress(compressConfig, true);
            takePhoto.onPickFromGallery();
            bottomDialog.dismiss();
        });
        RxView.clicks(photoDialogBinding.takePhoto).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
//            takePhoto.onPickFromCaptureWithCrop(imageUri,getCropOptions());
            File file = new File(Environment.getExternalStorageDirectory(), "/head/" + System.currentTimeMillis() + ".jpg");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Uri imageUri = Uri.fromFile(file);
            path = file.getAbsolutePath();
            CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(1080).create();
            takePhoto.onEnableCompress(compressConfig, true);
            takePhoto.onPickFromCapture(imageUri);
            bottomDialog.dismiss();
        });
        RxView.clicks(photoDialogBinding.cancel).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            bottomDialog.dismiss();
        });
        bottomDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        path = result.getImage().getCompressPath();
        Glide.with(this).load(new File(path)).into(activityCompanyAuthBinding.imgUpload);
        upload();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        path = null;
    }

    @Override
    public void takeCancel() {
        path = null;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }
}

